package example.config;

import example.model.MyUserDetail;
import example.service.MyUserDetailService;
import example.utils.Jwts_JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * TODO
 *
 * @author zgq
 * @date 2020/10/23 14:58
 */
@Slf4j
@Component
public class JwtAuthorizationTokenFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private Jwts_JWTUtil jwtUtil;
    @Autowired
    private MyUserDetailService myUserDetailService;

    public JwtAuthorizationTokenFilter(AuthenticationManager authenticationManager) {
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestHeaderToken = null;
        String str = httpRequest.getServletPath();
        // 登录请求 将 请求头设置 null, 否则获取请求头中的 token
        if (str.contains("/login")) {
            requestHeaderToken = null;
        } else {
            requestHeaderToken = httpRequest.getHeader("Authori-zation");
        }
        //如果不是登录请求 获取当前登陆人 的 登录账号，用于查询当前用户登录状态和用户信息
        String username = null;
        if (requestHeaderToken != null) {
            try {
                username = jwtUtil.getUserNameFromToke(requestHeaderToken);
                request.setAttribute("isValidToken", true);
            } catch (Exception e) {
                log.error(e.getMessage());
                request.setAttribute("isValidToken", false);
            }
        }
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication1 = context.getAuthentication();
        // 设置登录信息
//        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
        if (username != null) {
            MyUserDetail userDetails = (MyUserDetail) myUserDetailService.loadUserByUsername(username);
            if (jwtUtil.verifyToken(requestHeaderToken, username)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }
}
